package com.boot.config;

import com.boot.filter.StatelessAuthcFilter;
import com.boot.realm.MyRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        Map<String,Filter> filterMap = new HashMap<>();
        filterMap.put("statelessAuthcFilter",new StatelessAuthcFilter());

        factoryBean.setFilters(filterMap);

        Map<String,String> map = new HashMap<>();
        map.put("/login","anon");//登录可以直接访问
        map.put("/doc.html","anon");//登录可以直接访问
        map.put("/**","statelessAuthcFilter");//所有请求都走token验证

        factoryBean.setFilterChainDefinitionMap(map);

        factoryBean.setLoginUrl("/login");//登录接口

        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(@Autowired MyRealm myRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm);
        return manager;
    }

}